<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="销售" prop="sales"  v-hasPermi="['crm:resume:privilege']">
        <el-select :style="{width: '80px'}" v-model="queryParams.sales" placeholder="请输入归属销售">
          <el-option v-for="dict in dict.type.crm_sales" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker v-model="daterangeUpdateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['crm:resume:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['crm:resume:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['crm:resume:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['crm:resume:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入
        </el-button>
      </el-col>
      <el-col :span="1.5" >
        <el-button size="mini" @click="NullNumber">空手机
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resumeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile"/>
      <el-table-column label="应聘职位" align="center" prop="positionApplied"/>

      <el-table-column label="简历来源" align="center" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="250"/>

      <el-table-column label="销售" align="center" prop="userId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_sales" :value="scope.row.userId"/>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="updateTime" width="100">
        <!--<template slot-scope="scope">-->
        <!--<span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['crm:resume:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['crm:resume:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>


    <!-- 用户导入对话框 -->
    <!--    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>-->
    <!--      <el-upload-->
    <!--        :action="uploadFileUrl + '?updateSupport=' + check"-->
    <!--        :show-file-list="false"-->
    <!--        accept=".pdf,.xls"-->
    <!--        ref="file1"-->
    <!--        name="fileObj"-->
    <!--        :headers="headers"-->
    <!--        :on-success="batchInsert"-->
    <!--        :on-change="fileChange"-->
    <!--        :auto-upload="false"-->
    <!--        drag4-->
    <!--        multiple>-->
    <!--        <i class="el-icon-upload"></i>-->
    <!--        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
    <!--        <div class="el-upload__tip text-center" slot="tip">-->
    <!--          <div class="el-upload__tip" slot="tip">-->
    <!--            <el-checkbox :checked="check" v-model="check"/>-->
    <!--            是否同步至联系人-->
    <!--          </div>-->
    <!--          <span>仅允许导入xls、pdf格式文件。</span>-->
    <!--        </div>-->
    <!--      </el-upload>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="submitFileForm">确 定</el-button>-->
    <!--        <el-button @click="upload.open = false">取 消</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload :action="uploadFileUrl + '?updateSupport=' + check + '&' + 'updateLead='+ check2"
                 :show-file-list="false" accept=".pdf,.xls"
                 ref="file1" name="fileObj" :headers="headers" :on-success="batchInsert" :on-change="fileChange"
                 :auto-upload="false" drag multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox :checked="check" v-model="check"/>
            是否同步至联系人
          </div>

          <div class="el-upload__tip" slot="tip">
            <el-checkbox :checked="check2" v-model="check2"/>
            是否同步至订单追踪
          </div>
          <span>仅允许导入xls、pdf格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改简历信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名"/>
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                         :value="dict.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入手机号"/>
          </el-form-item>


          <el-form-item label="应聘职位" prop="positionApplied">
            <el-input v-model="form.positionApplied" placeholder="请输入应聘职位"/>
          </el-form-item>


          <el-form-item label="简历来源" prop="source">
            <el-select v-model="form.source" placeho lder="请选择简历来源">
              <el-option v-for="dict in dict.type.customer_source" :key="dict.value" :label="dict.label"
                         :value="dict.value" x></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售" prop="sales" v-hasPermi="['crm:resume:privilege']">
            <el-select v-model="form.sales" placeholder="请输入归属销售">
              <el-option v-for="dict in dict.type.crm_sales" :key="dict.value" :label="dict.label"
                         :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>

        </el-col>


        <el-col :span="16">
          <el-form-item label="简历全部信息" prop="resumeTxt">
            <el-input v-model="form.resumeTxt" type="textarea" resize="none" :rows="18" :readonly="true"/>
          </el-form-item>
        </el-col>


        <!--<el-form-item label="简历" v-if="form.id == null">-->
        <!--&lt;!&ndash;v-model="value11"&ndash;&gt;-->
        <!--&lt;!&ndash;:data="{id:form.id == null?0:form.id}"&ndash;&gt;-->
        <!--<el-upload-->
        <!--:action="uploadFileUrl"-->
        <!--:before-upload="handleBeforeUpload"-->
        <!--:file-list="fileList"-->
        <!--:limit="limit"-->
        <!--:on-error="handleUploadError"-->
        <!--:on-exceed="handleExceed"-->
        <!--:on-success="handleUploadSuccess"-->
        <!--:show-file-list="false"-->
        <!--:headers="headers"-->
        <!--class="upload-file-uploader"-->
        <!--name="fileObj"-->
        <!--ref="upload"-->
        <!--&gt;-->
        <!--&lt;!&ndash; 上传按钮 &ndash;&gt;-->
        <!--<el-button size="mini" type="primary">选取文件</el-button>-->
        <!--&lt;!&ndash; 上传提示 &ndash;&gt;-->
        <!--<div class="el-upload__tip" slot="tip" v-if="showTip">-->
        <!--请上传-->
        <!--<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>-->
        <!--<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>-->
        <!--的文件-->
        <!--</div>-->
        <!--</el-upload>-->

        <!--</el-form-item>-->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="el-upload__tip" slot="tip">
          <el-checkbox :checked="check" v-model="check"/>
          是否同步至联系人
        </div>

        <div class="el-upload__tip" slot="tip">
          <el-checkbox :checked="check2" v-model="check2"/>
          是否同步至订单追踪
        </div>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="批量上传结果" :visible.sync="dialogVisible1" @close="diaClose1" width="60%">
      <div v-html="errorInfo">

      </div>

    </el-dialog>


  </div>
</template>

<script>
import {
  listResume,
  getResume,
  delResume,
  addResume,
  updateResume,
  upload,
  getNullPhone
} from "../api/resume";

import {
  checkMobile
} from "../../zxbd/api/partner";
import {
  getToken
} from "@/utils/auth";

export default {
  name: "Resume",
  props: {
    // 值
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 1,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["xls", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  dicts: ['customer_source', 'sys_user_sex','crm_sales'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 简历信息表格数据
      resumeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 简历来源时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        mobile: null,
        updateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{
          required: true,
          message: "姓名不能为空",
          trigger: "blur"
        }],
        mobile: [{
          required: true,
          message: "手机号不能为空",
          trigger: "blur"
        }],
      },

      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/crm/resume/upload", // 上传的地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
      },
      fileList: [],
      value11: '',
      dialogVisible: false,
      dialogVisible1: false,
      contentStr: '',
      fileDatas: '',
      size: 0,
      errorInfo: '',
      check: true,
      check2: true
    };
  },
  watch: {
    value11: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = this.value11.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = {
                name: item,
                url: item
              };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
    this.getList();

  },
  methods: {
    /** 查询简历信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listResume(this.queryParams).then(response => {
        this.resumeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //空手机号
    NullNumber() {
      getNullPhone().then(response => {
        this.resumeList = response.data;
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.check = true
      this.upload.title = "简历导入";
      this.upload.open = true;
      console.log("check", this.check)
      console.log("check2", this.check2)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.value11 = ''
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        birthday: null,
        sex: null,
        mobile: null,
        positionApplied: null,
        source: null,
        filename: null,
        file: null,
        updateBy: null,
        updateTime: null,
        resumeTxt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加简历信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const id = row.id || this.ids
      getResume(id).then(response => {
        this.form = response.data;
        console.log(response.data)
        this.open = true;
        this.title = "修改简历信息";
      });
    },

    diaClose() {
      this.dialogVisible = false
    },
    diaClose1() {
      this.dialogVisible1 = false
      this.errorInfo = ''
      this.fileList = []
      this.$refs.file1.clearFiles()
      this.size = 0
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateResume(this.form, this.check,this.check2).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResume(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除简历信息编号为"' + ids + '"的数据项？').then(function () {
        return delResume(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/resume/export', {
        ...this.queryParams
      }, `resume_${new Date().getTime()}.xlsx`)
    },


    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed(files, fileList) {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.uploadList.push({
        name: res.fileName,
        url: res.fileName
      });
      if (res.code == 200) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.fileList = []
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.msgSuccess("上传成功");
        this.form = res.resume
      } else {
        this.$refs.upload.clearFiles()
        this.$modal.msgError("上传失败," + res.msg);
      }
      this.number = 0;
      this.$refs.file1.clearFiles()
      this.$modal.closeLoading()
    },

    // 删除文件
    handleDelete1(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    batchInsert() {
      this.size += 1
      if (this.size == this.fileList.length) {
        // console.log(111,this.fileList)
        let err_count = 0
        let succ_count = 0

        this.fileList.forEach((v, index) => {
          if (v.response.code == 200) {
            succ_count += 1
          } else {
            err_count += 1
            this.errorInfo += '名称' + err_count + ':&nbsp;&nbsp;' + v.name + ",原因:&nbsp;&nbsp;" + v.response.msg +
              "<br/>"
          }

        })

        this.upload.open = false;
        this.upload.isUploading = false;
        this.errorInfo = "共导入" + (this.fileList.length) + '条，成功' + succ_count + "条,失败" + err_count + "条。<br/>" + this
          .errorInfo
        this.dialogVisible1 = true
        this.$refs.file1.clearFiles()
        this.handleQuery()
      }

    },
    fileChange(file, filelist) {
      this.fileList = filelist
      // console.log(11,filelist)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.file1.submit();
    }

  }
};
</script>
